<?php
namespace app\controller;

use app\BaseController;
use OSS\OssClient;
use OSS\Core\OssException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class OssUpload extends BaseController {

private $accessKeyId = "LTAIKqhDnJgjiQvE";//AccessKeyId
	private $accessKeySecret;//AccessKeySecret
	private $endpoint;//地域节点名
	private $domain;//Bucket域名
	private $internalDomain;
	private $bucket;//Bucket名字

    function __construct(){
        $this->accessKeySecret = getenv("oss.secret");
        $this->endpoint = getenv("oss.endpoint");
        $this->domain = getenv("oss.domain");
        $this->internalDomain = getenv("oss.internalDomain");
        $this->bucket = getenv("oss.bucket");
    }
	/**
	 * 阿里云上传到OSS
	 * @param string $filePath 上传的文件路径
	 * @param string $fileName 上传的文件名称
	 * @return string 返回绝对路径
	 */
	protected function OssUpload(string $filePath, string $fileName): string
	{
		if(!file_exists($filePath)) return "";
		try {
			$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
			$object = date("sc_files/Y/m/d/").substr(md5(time()),0,6)."_".$fileName;
			$content = file_get_contents($filePath);
			$ossClient->putObject($this->bucket, $object, $content);
			return $object;
		} catch (OssException $e) {
			return "";
		}
	}

	/**
	 * oss文件删除
	 * @param int $id files表中的id
	 * @return bool
	 */
	protected function OssDelete(int $id): bool
	{
		try {
			$data = $this->M("files")->where("id",$id)->field("path")->find();
			if(empty($data))return false;
			$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
			$ossClient->deleteObject($this->bucket,$data['path']);
			$this->M("files")->where("id", $id)->delete();
		} catch (OssException | DbException $e) {
			return false;
		}
		return true;
	}
	public function MultiUpload(){
		$limit = 1024 * 1024 * 5;
		$total_size = $this->request->post("total");//分段总数
		$current_size = $this->request->post("current");//当前分段
		$each_size = $this->request->post("each");
		if($each_size==0||$each_size>$limit)pr(300,"分段大小不能超过");
		$file = $_FILES['file'];
		if($file['error']>0){
			pr(300,"文件上传出错");
		}
		$uid = $this->GetUid();
		$size = $file['file_size'];
		$path = $this->OssUpload($file['tmp_name'],$file['file_name']);
		if(empty($path))pr(301,"上传失败");
		else{
			$id = $this->M("files")->insert(['path'=>$path,'uid'=>$uid,'size'=>$size,'downTimes'=>0]);
            return json_encode( pr(200,"上传成功,id ".$id,$_FILES));
		}
	}
	/**
	 * 前端上传接口
	 *
	 */
	public function Upload(){
		$file = $_FILES['file'];
		if($file['error']>0){
            return json_encode( pr(300,"文件上传出错"));
		}
		$uid = $this->GetUid();
		$size = $file['file_size'];
		$path = $this->OssUpload($file['tmp_name'],$file['file_name']);
		if(empty($path))pr(301,"上传失败");
		else{
			$id = $this->M("files")->insert(['path'=>$path,'uid'=>$uid,'size'=>$size,'downTimes'=>0]);
            return json_encode( pr(200,"上传成功,id ".$id,$_FILES));
		}
	}

	/**
	 * 下载文件
	 * @param int $id files表中的id
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	public function Download(int $id){
		$data = $this->M("files")->where("id",$id)->field("path,downTimes")->find();
		if(empty($data))pr(300,"文件不存在");
		$this->M("files")->where("id",$id)->save(['downTimes'=>$data['downTimes']+1]);
		response(file_get_contents("https://".$this->internalDomain."/".$data['path']),200,["Content-Type"=>"application/octet-stream"]);
	}
}